/* Description: getopt_long测试
 * Author: zhouhui
 * Release Date: 2014-09-08
 * Modify log: 
 */ 

#define _GNU_SOURCE
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>

/*
 * 支持 --file file [file...]   (-f)
 *      --perm [perm...] (-p) //defaut 750
 *      --append   (-a)
 *      --help (-h)
 */
int main(int argc, char **argv)
{
    struct option opt[] = {
        {"file",1,NULL,'f'},
        {"perm",2,NULL,'p'},
        {"append",0,NULL,'a'},
        {"help",0,NULL,'h'}
    };

    int ret,tmp=1,last=0;
    while((ret = getopt_long(argc,argv,"f:ah",opt,&last)) != -1)
    {
        switch (ret){
            case 'f':
               printf("\033[1;31m--file "); 
               for (;tmp<=optind; tmp++)
               {
                   printf("%s ",argv[tmp+1]);
               }
               printf("\033[0m\n"); 
               break;
            case 'p':
               printf("\033[7m--perm %s\033[0m\n",optarg); 
               break;
            case 'a':
               printf("\033[1;33m--append\033[0m\n"); 
               break;
            case '?':
                ;
            case 'h' :
                printf("-f/--file file [file...]  : files\n" 
                       "-p/--perm [perm...]  : permition ,default 750\n"
                       "-a/--append\n"
                       "-h/--help\n");
                break;
        }
        tmp = optind;
       // printf("ret=%c optarg=%s optind=%d last=%d\n",ret,optarg,optind,last);
    }
    
    printf("------------------------------\n");
    char **p;
    for (p=&argv[1]; *p != NULL; p++)
        printf("%s\n",*p);

    return 0;
}
